/*
 * client_mgr.h
 *
 *  Created on: Aug 2, 2013
 *      Author: killerg
 */

#ifndef AUTH_MGR_H_
#define AUTH_MGR_H_

#include "share/json/json.h"
#include "share/db_mgr.h"
#include "share/http_c3.h"
#include "share/co.pb.h"
#include "share/patterns.h"

struct auth_mgr_t {
    struct account_t {
        std::string account;
        std::string passwd;
        int32_t playerid = -1;
    };

    typedef std::function<void(int32_t playerid, const std::string &account, const std::string &mc, const std::string &data)> auth_cb_t;
    typedef void (*auth_fun_t)(const Json::Value &data, auth_mgr_t::auth_cb_t cb);

    bool init();
    void destroy();
    void update();

    void get_account(
            const char* account,
            std::function<void(db_error_t, const account_t&)> cb);

    void add_account(
            const char* account,
            const char* passwd,
            std::function<void(db_error_t, int32_t)> cb);

    auth_fun_t get_fun(co::EPlatformId epid) {
        auto itr = funs.find(epid);
        if (itr == funs.end())
            return NULL;

        return itr->second;
    }

    struct cache_item_t {
        std::string account = "";
        std::string passwd = "";
        int32_t playerid = -1;
        int32_t hit_count = 0;
    };
    ptr_map<std::string, cache_item_t*, std::unordered_map<std::string, cache_item_t*>> cache;
    std::set<std::string> pending;
    http_client3 http;

    struct signin_cache_t {
    	std::string mc;
    	time_t create;
    	time_t last_signin;
    };
    ptr_map<std::string, signin_cache_t*, std::unordered_map<std::string, signin_cache_t*>> signin_cache;
    void signin(const std::string &mc);

    int dbget_num = 0;
    int dbadd_num = 0;
    int httpop_num = 0;
    int authed_ps = 0;
    int authing = 0;

    db_mgr_t db;
private:
    void _save_maxid();
    void _return_id(int32_t id);
    int32_t _alloc_id();
    int32_t maxid;
    std::list<int32_t> valid_id;


    std::map<co::EPlatformId, auth_fun_t> funs;

    bool _inited = false;
};

#endif /* AUTH_MGR_H_ */
